// import { Modal } from 'antd';
// export interface SelectObjProps {
//   orgId: string;
//   open: (param: any) => void;
//   onCancel: () => void;
//   onOk: () => void;
// }
import { aiStudyApi } from '@/api';
import IconFont from '@/components/IconFont';
import { useCreation, useSelections } from 'ahooks';
import type { PaginationProps } from 'antd';
import { Checkbox, Empty, Input, Pagination, Spin } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import OStyle from './index.less';
export type SelobjRef = {
  onSubmit: () => Promise<any>;
};
let data: any[] = [];
let value = '';
let openedData: any[] = [];
const SelectObj = forwardRef<SelobjRef, any>((props, ref) => {
  const [leftData, setLeftData] = useState<any[]>([]);
  // const [openedData, setOpenedData] = useState<any[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState<number>(10);
  console.log(props, '打印看看返回的参数');
  const [secList, setSecList] = useState<any[]>([]);
  // let [seledKey, setSeledKey] = useState<number>(0);
  // const [value, { onChange }] = useEventTarget({ initialValue: '' });
  // const [value, setValue] = useState<string>('');
  const loading = false;
  const refresh = () => {
    console.log('刷新按钮');
  };

  const filterList = useCreation(() => {
    if (value) {
      return (
        data?.filter((v: any) => {
          return v.entName.indexOf(value) !== -1;
        }) ?? []
      );
    } else {
      return data?.slice() ?? [];
    }
  }, [value, data]);
  // const onInputChange = (e) => {
  //   console.log(e, '打印看看输入框');
  //   // getStudyObjList(1, pageSize);
  // };
  const { selected, allSelected, isSelected, toggle, toggleAll, partiallySelected, setSelected, unSelect } =
    useSelections(
      filterList.map((v: any) => v.entId),
      [],
    );
  // let secList = useCreation(() => {
  //   console.log(selected, openedData, '打印看看是什么');
  //   return openedData?.filter((v: any) => selected.includes(v.entId as never)) ?? [];
  // }, [selected]);
  // useEffect(() => {
  //   setSecList(openedData?.filter((v: any) => selected.includes(v.entId as never)) ?? []);
  // }, [selected]);
  const onSubmit = () => {
    console.log(secList, '打印看看列表');
    return Promise.resolve(secList);
  };
  const getStudyObjList = (current: number, pageSize: number) => {
    setLeftData([]);
    aiStudyApi
      .getStudyObjList({ studyObject: props.objtype, entName: value, pageNum: current, pageSize: pageSize })
      .then((res: any) => {
        console.log(openedData, '的点点滴滴');
        setLeftData(res.data.list);
        const arr = [...openedData];
        res.data.list.forEach((el: any) => {
          if (!arr.some((item) => item.entId == el.entId)) arr.push(el);
        });
        openedData = arr;
        setTotal(res.data.total);
        data = res.data.list;
        // setTimeout(() => {
        //   setSecList(openedData?.filter((v: any) => selected.includes(v.entId as never)) ?? []);
        //   console.log(openedData, selected, secList, '打印看看咋样了');
        //   setSeledKey(++seledKey);
        // }, 2000);
      });
  };
  // useEffect(() => {

  // }, [selected]);
  useImperativeHandle(ref, () => ({
    onSubmit,
  }));
  // const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
  //   console.log(current, pageSize, '打印看看');
  //   setDefaultPageSize(pageSize);
  //   getStudyObjList(current, pageSize);
  // };
  const onPageChange: PaginationProps['onChange'] = (current, pageSize) => {
    console.log(current, pageSize, '打印看看第几页');
    setCurrent(current);
    setPageSize(pageSize);
    getStudyObjList(current, pageSize);
  };
  useEffect(() => {
    console.log(openedData, selected, allSelected, '打印看看');
    if (selected.length > 200) {
      const arr = [...selected];
      arr.splice(arr.length - 1, 1);
      setSelected(arr);
    } else setSecList(openedData?.filter((v: any) => selected.includes(v.entId as never)) ?? []);
  }, [openedData, selected, allSelected]);
  useEffect(() => {
    value = '';
    if (JSON.parse(props.objs).length > 0) {
      const arr = JSON.parse(props.objs);
      openedData = [...arr];
    }
    if (!props.ids) setSelected([]);
    else setSelected(props.ids.split(','));
    getStudyObjList(1, 10);
  }, []);
  return (
    <div className={OStyle.selectOrgStaff} style={{ padding: '16px 20px' }}>
      <div className={OStyle.main} style={{ width: 640, height: 400 }}>
        <div className={OStyle.boxArea} style={{ paddingRight: 11 }}>
          <div className={OStyle.title}>选择:</div>
          <div className={OStyle.panel} style={{ height: 'calc(100% - 40px)' }}>
            <div
              style={{
                padding: '0 11px',
                height: 54,
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <Input
                allowClear
                onChange={(e) => {
                  value = e.target.value;
                  console.log(e.target.value, '打印看看输入框');
                  getStudyObjList(1, pageSize);
                }}
                prefix={<IconFont type="icon-search"></IconFont>}
                placeholder="名称筛选"
              />
              <IconFont
                width={32}
                height={32}
                type="icon-refresh"
                size={20}
                onClick={() => {
                  refresh();
                  getStudyObjList(current, pageSize);
                }}
                style={{ marginLeft: 8 }}
              ></IconFont>
            </div>
            <div className={OStyle.listArea} style={{ height: 'calc(100% - 68px)' }}>
              <div
                style={{
                  paddingLeft: 11,
                  paddingBottom: 4,
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                <span onClick={toggleAll} style={{ display: 'inline-flex', alignItems: 'center' }}>
                  <Checkbox checked={allSelected} indeterminate={partiallySelected}></Checkbox>
                  <span style={{ cursor: 'pointer', marginLeft: 6 }}>全选</span>
                </span>
              </div>
              <ul className={OStyle.list}>
                {loading ? (
                  <div className={OStyle.flexCenter} style={{ height: 160 }}>
                    <Spin></Spin>
                  </div>
                ) : leftData?.length ? (
                  leftData?.map((v: any) => {
                    return (
                      <li
                        key={v.entId}
                        className={OStyle.listItem}
                        onClick={() => {
                          toggle(v.entId as never);
                        }}
                      >
                        <div
                          style={{
                            width: '100%',
                            display: 'flex',
                            alignItems: 'center',
                          }}
                        >
                          <Checkbox
                            checked={isSelected(v.entId)}
                            onChange={() => {
                              // if (selected.length >= 15) {
                              //   const arr = selected;
                              //   arr.pop();
                              //   setSelected(arr);
                              // }
                            }}
                          ></Checkbox>
                          {/* <img className={OStyle.head - icon} src={v.hdpic || userAvator} alt="icon" /> */}
                          {/* <span className={OStyle.item - name} style={{ width: `calc(100% - 160px)` }} title={v.name}>
                            {v.name}
                          </span> */}
                          <span style={{ width: 265, marginLeft: 8 }}>{v.entName}</span>
                        </div>
                      </li>
                    );
                  })
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
                )}
              </ul>
              <Pagination
                showSizeChanger
                // onShowSizeChange={onShowSizeChange}
                current={current}
                pageSize={pageSize}
                onChange={onPageChange}
                total={total}
                simple
              />
            </div>
          </div>
        </div>
        <div className={OStyle.secArea} style={{ paddingLeft: 11 }}>
          <div className={OStyle.title}>已选:</div>
          <div className={OStyle.panel} style={{ height: 'calc(100% - 40px)', overflowY: 'auto' }}>
            <ul className={OStyle.list}>
              {secList?.map((v: any) => {
                return (
                  <li key={v.entId} className={OStyle.listItem} style={{ display: 'flex', alignItems: 'center' }}>
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        width: 'calc(100% - 32px)',
                      }}
                    >
                      {/* <img className={OStyle.head-icon} src={v.hdpic || userAvator} alt="头像" /> */}
                      {/* <span className={OStyle.itemName} style={{ width: 'calc(100% - 136px)' }} title={v.name}>
                        {v.entName}
                      </span> */}
                      <span style={{ width: 265 }}>{v.entName}</span>
                    </div>
                    <IconFont
                      width={32}
                      height={32}
                      size={20}
                      type="icon-close"
                      color="#fa541c"
                      style={{ cursor: 'pointer' }}
                      onClick={() => {
                        unSelect(v.entId as never);
                      }}
                    ></IconFont>
                  </li>
                );
              })}
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
});

export default SelectObj;
// function onChange(event: ChangeEvent<HTMLInputElement>): void {
//   throw new Error('Function not implemented.');
// }
